<!-- 部门管理 -->
<template>
  <div class="department-page art-full-height">
    <ElRow :gutter="12" class="dept-layout">
      <!-- 左侧部门树 -->
      <ElCol :xs="24" :sm="24" :md="8" :lg="6" :xl="5">
        <ElCard shadow="never" class="dept-tree-card">
          <template #header>
            <div class="card-header">
              <span class="title">部门结构</span>
              <ElSpace>
                <ElButton 
                  type="primary" 
                  size="small" 
                  @click="showDeptDialog('add')"
                  v-ripple
                >
                  新增部门
                </ElButton>
                <ElButton 
                  size="small" 
                  :icon="Refresh" 
                  @click="loadDeptTree"
                  v-ripple
                />
              </ElSpace>
            </div>
          </template>

          <!-- 部门树 -->
          <ElTree
            ref="deptTreeRef"
            :data="deptTreeData"
            :props="treeProps"
            node-key="id"
            :highlight-current="true"
            :expand-on-click-node="false"
            default-expand-all
            @node-click="handleDeptClick"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <span class="node-label">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ node.label }}</span>
                </span>
                <ElSpace class="node-actions">
                  <ElButton
                    type="primary"
                    text
                    size="small"
                    @click.stop="showDeptDialog('add', data)"
                  >
                    <el-icon><Plus /></el-icon>
                  </ElButton>
                  <ElButton
                    type="primary"
                    text
                    size="small"
                    @click.stop="showDeptDialog('edit', data)"
                  >
                    <el-icon><Edit /></el-icon>
                  </ElButton>
                  <ElButton
                    type="danger"
                    text
                    size="small"
                    @click.stop="deleteDept(data)"
                  >
                    <el-icon><Delete /></el-icon>
                  </ElButton>
                </ElSpace>
              </div>
            </template>
          </ElTree>
        </ElCard>
      </ElCol>

      <!-- 右侧员工列表 -->
      <ElCol :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
        <!-- 搜索栏 -->
        <EmployeeSearch
          v-show="showSearchBar"
          v-model="searchForm"
          @search="handleSearch"
          @reset="resetSearch"
        />

        <ElCard
          class="art-table-card"
          shadow="never"
        >
          <!-- 表格头部 -->
          <ArtTableHeader
            v-model:columns="columnChecks"
            v-model:showSearchBar="showSearchBar"
            :loading="loading"
            @refresh="refreshData"
          >
            <template #left>
              <div class="dept-info">
                <span class="dept-name">{{ currentDeptName || '全部员工' }}</span>
                <span class="dept-count">（共 {{ pagination.total }} 人）</span>
              </div>
            </template>
          </ArtTableHeader>

            <ArtTable
                :loading="loading"
                :data="data"
                :columns="columns"
            />
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 部门编辑弹窗 -->
    <DeptDialog
      v-model:visible="deptDialogVisible"
      :type="deptDialogType"
      :dept-data="currentDeptData"
      :dept-tree="deptTreeData"
      @submit="handleDeptDialogSubmit"
    />
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Refresh, OfficeBuilding, Plus, Edit, Delete } from '@element-plus/icons-vue'
  import { useTable } from '@/composables/useTable'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import EmployeeSearch from './modules/employee-search.vue'
  import DeptDialog from './modules/dept-dialog.vue'
  import {
    apiDeptTreeDataUsingPost,
    apiDeptDeleteDataUsingPost,
    apiEmployeeGetPageUsingPost,
    type ApiDeptTreeVo,
    type ApiEmployee
  } from '@/api'

  defineOptions({ name: 'Department' })

  type DeptTreeItem = ApiDeptTreeVo
  type EmployeeListItem = ApiEmployee

  // 部门树相关
  const deptTreeRef = ref()
  const deptTreeData = ref<DeptTreeItem[]>([])
  const currentDeptId = ref<number | undefined>(undefined)
  const currentDeptName = ref<string>('')

  const treeProps = {
    children: 'children',
    label: 'deptName'
  }

  // 搜索表单
  const searchForm = ref({
    employeeName: undefined,
    employeePhone: undefined
  })

  const showSearchBar = ref(false)

  // 部门弹窗相关
  const deptDialogVisible = ref(false)
  const deptDialogType = ref<'add' | 'edit'>('add')
  const currentDeptData = ref<DeptTreeItem | undefined>(undefined)

  // 员工表格
   const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    resetSearchParams,
    refreshData
  } = useTable({
    core: {
      apiFn: apiEmployeeGetPageUsingPost,
      apiParams: {
        body: {
          deptId: undefined
        }
      },
      paginationWrapper: 'body',
      immediate: false,
      columnsFactory: () => [
        { type: 'index', width: 60, label: '序号' },
        {
          prop: 'loginName',
          label: '账号',
          minWidth: 120
        },
        {
          prop: 'employeeName',
          label: '名称',
          minWidth: 120
        },
        {
          prop: 'employeeGender',
          label: '性别',
          width: 80,
          formatter: (row: EmployeeListItem) => {
            const genderMap: Record<number, string> = {
              0: '女',
              1: '男'
            }
            return genderMap[row.employeeGender as number] || '未知'
          }
        },
        {
          prop: 'employeePhone',
          label: '手机号',
          minWidth: 120
        },
        {
          prop: 'deptName',
          label: '部门',
          minWidth: 120
        },
        {
          prop: 'positionId',
          label: '职务',
          minWidth: 100
        },
        {
          prop: 'tags',
          label: '标签',
          minWidth: 120
        },
        {
          prop: 'disabledFlag',
          label: '状态',
          width: 80,
          formatter: (row: EmployeeListItem) =>
            h(
              'span',
              {
                class: row.disabledFlag === 1 ? 'status-disabled' : 'status-active'
              },
              row.disabledFlag === 1 ? '已禁用' : '正常'
            )
        },
        {
          prop: 'createTime',
          label: '创建时间',
          width: 180,
          sortable: true
        }
      ]
    }
  })

  /**
   * 加载部门树
   */
   const loadDeptTree = async () => {
    try {
      const res = await apiDeptTreeDataUsingPost({})
      console.log('部门树数据:', res)
      if (res) {
        deptTreeData.value = res
        
        // 如果有部门数据且当前没有选中任何部门，则默认选中第一个部门
        if (res.length > 0 && currentDeptId.value === undefined) {
          const firstDept = res[0]
          handleDeptClick(firstDept)
          
          // 设置树节点的选中状态
          nextTick(() => {
            if (deptTreeRef.value) {
              deptTreeRef.value.setCurrentKey(firstDept.id)
            }
          })
        }
      }
    } catch (error) {
      console.error('加载部门树失败:', error)
      ElMessage.error('加载部门树失败')
    }
  }

  /**
   * 点击部门节点
   */
  const handleDeptClick = (data: DeptTreeItem) => {
    console.log('选中部门:', data)
    currentDeptId.value = data.id
    currentDeptName.value = data.deptName || ''
    
    // 更新搜索参数
    if (!searchParams.body) {
      searchParams.body = {}
    }
    searchParams.body.deptId = data.id
    
    // 重新加载员工数据
    refreshData()
  }

  /**
   * 显示部门对话框
   */
  const showDeptDialog = (type: 'add' | 'edit', data?: DeptTreeItem) => {
    deptDialogVisible.value = true
    deptDialogType.value = type
    currentDeptData.value = data
  }

  /**
   * 部门对话框提交成功
   */
  const handleDeptDialogSubmit = () => {
    loadDeptTree()
    // 如果当前选中了部门，重新加载员工数据
    if (currentDeptId.value) {
      refreshData()
    }
  }

  /**
   * 删除部门
   */
  const deleteDept = (data: DeptTreeItem) => {
    ElMessageBox.confirm(
      `确定删除部门"${data.deptName}"吗？删除后该部门下的子部门也将被删除！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        try {
          const res = await apiDeptDeleteDataUsingPost({
            body: { id: data.id }
          })
          if (res) {
            ElMessage.success('删除成功')
            loadDeptTree()
            // 如果删除的是当前选中的部门，清空员工列表
            if (currentDeptId.value === data.id) {
              currentDeptId.value = undefined
              currentDeptName.value = ''
              // 清空员工数据
              refreshData()
            }
          } else {
            ElMessage.error('删除失败')
          }
        } catch (error) {
          console.error('删除部门失败:', error)
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
  }

  /**
   * 搜索处理
   */
  const handleSearch = (params: Record<string, any>) => {
    console.log('搜索参数:', params)
    if (!searchParams.body) {
      searchParams.body = {}
    }
    Object.assign(searchParams.body, params)
    // 保持部门ID
    searchParams.body.deptId = currentDeptId.value
    refreshData()
  }

  /**
   * 重置搜索
   */
  const resetSearch = () => {
    resetSearchParams()
    // 保持部门ID
    if (!searchParams.body) {
      searchParams.body = {}
    }
    searchParams.body.deptId = currentDeptId.value
    refreshData()
  }

  // 初始化加载部门树
  onMounted(() => {
    loadDeptTree()
  })
</script>

<style lang="scss" scoped>
  .department-page {
    padding-bottom: 15px;

    .dept-layout {
      height: 100%;
    }

    .dept-tree-card {
      height: calc(100vh - 120px);
      overflow-y: auto;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-weight: 600;
          font-size: 16px;
        }
      }

      :deep(.el-tree) {
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;

          .node-label {
            display: flex;
            align-items: center;
            gap: 6px;
          }

          .node-actions {
            opacity: 0;
            transition: opacity 0.2s;
          }

          &:hover .node-actions {
            opacity: 1;
          }
        }
      }
    }

    .dept-info {
      display: flex;
      align-items: baseline;
      gap: 8px;

      .dept-name {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .dept-count {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }

    .status-active {
      color: var(--el-color-success);
    }

    .status-disabled {
      color: var(--el-color-danger);
    }
  }
</style>
